package cn.controller;

import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.kpi.service.sys.IOrgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import cn.common.ConfigOption;
import cn.common.ExceResult;
import cn.common.ExceStatisResult;
import cn.common.LayTable;
import cn.filter.LoginCheck;
import cn.kpi.entity.loan.LoanUserListEntity;
import cn.kpi.entity.sys.MenuEntity;
import cn.kpi.entity.sys.OrgEntity;
import cn.kpi.entity.sys.RoleEntity;
import cn.kpi.entity.sys.UserEntity;
import cn.kpi.entity.usualassessment.UserUATMzpdSummaryEntity;
import cn.kpi.service.loan.ILoanUserService;
import cn.kpi.service.sys.IAccountService;
import cn.kpi.service.sys.IStatisService;

@Controller
public class IndexController {
	@Autowired
	private IOrgService iOrgService;

	@Autowired
	private IAccountService iAccountService;

	@Autowired
	private ILoanUserService iLoanUserService;

	@Autowired
	private IStatisService iStatisService;

	@RequestMapping(value = "/index")
	public String Index(HttpServletRequest request, Model model) {
		try {
			Object userido = request.getSession().getAttribute("UserId");
			Long userid = Long.parseLong(userido.toString());
			List<MenuEntity> list = iAccountService.GetMenuByUserId(userid);

			UserEntity user = (UserEntity) request.getSession().getAttribute("UserEntity");

			List<MenuEntity> listparent = new ArrayList<MenuEntity>();
			List<MenuEntity> listchild = new ArrayList<MenuEntity>();

			String homeurl = "adminhome";

			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getLevel() == 1) {
					if (!list.get(i).getMenuname().endsWith("首页")) {
						listparent.add(list.get(i));
					} else {
						if (user.getUserid() > 0) {
							homeurl = list.get(i).getUrl();
						}
					}

				} else if (list.get(i).getLevel() > 1) {
					listchild.add(list.get(i));
				}
			}

			model.addAttribute("listparent", listparent);
			model.addAttribute("listchild", listchild);
			model.addAttribute("user", user);
			model.addAttribute("homeurl", homeurl);

			// 借调到期提醒
			int txcount = 0;
			String where = "";
			if (user.getUserid() > 0) {
				String strorgids = iAccountService.GetOrgidsByUserRoleId(user.getRoleid());
				where = " AND userid IN (SELECT userid FROM t_sys_user WHERE szdw IN (" + strorgids + "))";
			}

			List<LoanUserListEntity> lstloan = iLoanUserService.GetUserLoanListDq(where);

			txcount = lstloan.size();
			model.addAttribute("txcount", txcount);

		} catch (Exception ex) {

		}

		return "index";
	}

	@LoginCheck(description = false)
	@RequestMapping(value = "/login")
	public String Login() {
		return "login";
	}

	@RequestMapping(value = "/adminhome")
	public String AdminHome(HttpServletRequest request, Model model) {
		UserEntity user = (UserEntity) request.getSession().getAttribute("UserEntity");
		model.addAttribute("userhome", user);
		return "adminhome";
	}

	@RequestMapping(value = "/normalhome")
	public String NormalHome() {
		return "normalhome";
	}

	@RequestMapping(value = "/changepwd")
	public String ChangePwd() {
		return "changepwd";
	}

	@RequestMapping(value = "/change_userpwd")
	public String ChangeUserpwd(HttpServletRequest request, HttpServletResponse response) {
		try {
			String userpwd = request.getParameter("pwd").trim();
			Object userido = request.getSession().getAttribute("UserId");
			Long userid = Long.parseLong(userido.toString());
			int iResult = iAccountService.ChangePwd(userid, userpwd);
			return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
		} catch (Exception ex) {
			return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
		}
	}

	@RequestMapping(value = "/userloginout")
	public String UserLoginOut(HttpServletResponse response, HttpServletRequest request) {
		Enumeration em = request.getSession().getAttributeNames();
		while (em.hasMoreElements()) {
			request.getSession().removeAttribute(em.nextElement().toString());
		}
		return "redirect:/login";
	}

	@LoginCheck(description = false)
	@RequestMapping(value = "/userlogin")
	public String UserLogin(HttpServletResponse response, HttpServletRequest request) {
		try {
			String username = request.getParameter("username");
			String userpwd = request.getParameter("userpwd");
			String code = request.getParameter("code");
			if (username == null || username.length() <= 0) {
				return renderStringScript(response, "<script>top.Diaolog(1,'用户名为空')</script>");
			}
			if (userpwd == null || userpwd.length() <= 0) {
				return renderStringScript(response, "<script>top.Diaolog(2,'密码为空')</script>");
			}
			if (code == null || code.length() <= 0) {
				return renderStringScript(response, "<script>top.Diaolog(3,'验证码为空')</script>");
			}

			Object imgcode = request.getSession().getAttribute("imgcode");
			if (imgcode == null) {
				return renderStringScript(response, "<script>top.Diaolog(3,'验证码失效，请重新获取')</script>");
			}
			String strcode = imgcode.toString();
			if (!strcode.equals(code)) {
				return renderStringScript(response, "<script>top.Diaolog(3,'验证码不正确')</script>");
			}

			UserEntity entity = new UserEntity();

			if (username.equals(ConfigOption.getInstance().getSuperadmin())
					&& userpwd.equals(ConfigOption.getInstance().getSuppwd())) {
				entity.setUserid(0);
				entity.setUsername(ConfigOption.getInstance().getSuperadmin());
				entity.setUserpwd(ConfigOption.getInstance().getSuppwd());
				entity.setRealname("开发维护人员");
				entity.setRoleid(0L);
				entity.setUsertype(3);// 类型系统管理员
			} else {
				entity = iAccountService.UserLogin(username);
				if (entity == null) {
					return renderStringScript(response, "<script>top.Diaolog(1,'用户名错误')</script>");
				}

				if (!entity.getUserpwd().equals(userpwd)) {
					return renderStringScript(response, "<script>top.Diaolog(2,'密码错误')</script>");
				}
			}

			// List<RoleEntity>
			// lstRole=iAccountService.GetRoleByUserId(entity.getUserid());
			//
			// int roletype=0;
			// for(int i=0;i<lstRole.size();i++){
			// if(lstRole.get(i).getRoletype()>roletype){
			// roletype=lstRole.get(i).getRoletype();
			// }
			// }
			//
			// entity.setMaxroletype(roletype);
			//
			//
			// String
			// orgids=iAccountService.GetOrgidsByRoleId(entity.getUserid(),
			// entity.getSzdw());
			// System.out.println(orgids);

			request.getSession().setAttribute("UserEntity", entity);
			request.getSession().setAttribute("UserId", entity.getUserid());
			// request.getSession().setAttribute("roletype", roletype);

			return renderStringScript(response, "<script>top.location.href='index'</script>");
		} catch (Exception ex) {
			return renderStringScript(response, "<script>top.Diaolog(4,'网络繁忙，请稍后重试')</script>");
		}
	}

	@ResponseBody
	@RequestMapping(value = "/getstatisdata")
	public ExceStatisResult<Map<String, List<Map>>> GetStatisData(HttpServletRequest request,
			HttpServletResponse response) {
		ExceStatisResult<Map<String, List<Map>>> result = new ExceStatisResult<Map<String, List<Map>>>();
		result.setCode(400);
		result.setResult(0);
		try {
			String where = "";
			where += GetUserListByRole();
			
			List<Map> ageMap = iStatisService.GetAgeList(where);
			List<Map> dyMap = iStatisService.GetDyList(where);
			List<Map> xlMap = iStatisService.GetXlList(where);

			String where1 = " AND userid IN(SELECT userid FROM t_sys_user WHERE 1=1 "+GetUserListByRole()+")";
			Calendar cale = Calendar.getInstance();          
			int year = cale.get(Calendar.YEAR);          
			int month = cale.get(Calendar.MONTH);
			if(month==0){
				year=year-1;
				month=12;
			}
			where1+=" AND year="+year+" AND mouth="+month+" AND status=2";

			List<Map> ymkqjzMap = iStatisService.GetYmkqjzList(where1);
			
			Map<String, List<Map>> data = new HashMap<String, List<Map>>();
			data.put("ageMap", ageMap);
			data.put("dyMap", dyMap);
			data.put("xlMap", xlMap);
			data.put("ymkqjzMap", ymkqjzMap);
			
			UserEntity entity = getWebSysUserAttribute("UserEntity");
			if(entity.getUserid()==1473){
				int year1 = cale.get(Calendar.YEAR);
				int month1 = cale.get(Calendar.MONTH)+1;
			    int year1pre=year1;
			    int month1pre=month1-1;
			    if(month1pre==0){
			    	year1pre=year1-1;
			    	month1pre=12;
			    }
				String where2=" AND createtime<'"+year1+"-"+month1+"-06 00:00:00' AND createtime>='"+year1pre+"-"+month1pre+"-01 00:00:00'";
				where2+=" AND userid IN(SELECT userid FROM t_sys_user WHERE 1=1 "+GetUserListByRole()+")";
				where2+=" AND status=2";
				List<Map> kqjzqkMap = iStatisService.GetKqjzqkListByWhere(where2,year1,month1);
				data.put("kqjzqkMap", kqjzqkMap);
			}

			result.setCode(200);
			result.setResult(1);
			result.setMsg("操作成功");
			result.setItems(data);
		} catch (Exception ex) {
			result.setCode(500);
			result.setResult(0);
			result.setMsg("操作异常");
		}
		return result;
	}


	@ResponseBody
	@RequestMapping(value = "/getstatisdatabyorg")
	public ExceStatisResult<Map<String, List<Map>>> GetStatisDatabyOrgid(HttpServletRequest request,
																  HttpServletResponse response) {
		ExceStatisResult<Map<String, List<Map>>> result = new ExceStatisResult<Map<String, List<Map>>>();
		result.setCode(400);
		result.setResult(0);
		try {
			String where = "";

			String orgidstr = request.getParameter("orgid");
			if (orgidstr != null && orgidstr.length() > 0 && !orgidstr.equals("0")) {
				OrgEntity orgentity=iOrgService.GetOrgById(Long.parseLong(orgidstr));
				where+=" AND szdw IN (SELECT orgid FROM t_sys_org WHERE lft>= "+orgentity.getLft()+" AND lft<="+orgentity.getRgt()+")";
			} else {
				where += GetUserListByRole();
			}

			List<Map> ageMap = iStatisService.GetAgeList(where);
			List<Map> dyMap = iStatisService.GetDyList(where);
			List<Map> xlMap = iStatisService.GetXlList(where);

			String where1 = "";
			if (orgidstr != null && orgidstr.length() > 0 && !orgidstr.equals("0")) {
				OrgEntity orgentity=iOrgService.GetOrgById(Long.parseLong(orgidstr));
				where1+=" AND userid IN (SELECT userid FROM t_sys_user where szdw in(SELECT orgid FROM t_sys_org WHERE lft>= "+orgentity.getLft()+" AND lft<="+orgentity.getRgt()+"))";
			} else {
				where1 += " AND userid IN(SELECT userid FROM t_sys_user WHERE 1=1 "+GetUserListByRole()+")";;
			}

			Calendar cale = Calendar.getInstance();
			int year = cale.get(Calendar.YEAR);
			int month = cale.get(Calendar.MONTH);
			if(month==0){
				year=year-1;
				month=12;
			}
			where1+=" AND year="+year+" AND mouth="+month+" AND status=2";

			List<Map> ymkqjzMap = iStatisService.GetYmkqjzList(where1);

			Map<String, List<Map>> data = new HashMap<String, List<Map>>();
			data.put("ageMap", ageMap);
			data.put("dyMap", dyMap);
			data.put("xlMap", xlMap);
			data.put("ymkqjzMap", ymkqjzMap);

			UserEntity entity = getWebSysUserAttribute("UserEntity");
			if(entity.getUserid()==1473){
				int year1 = cale.get(Calendar.YEAR);
				int month1 = cale.get(Calendar.MONTH)+1;
				int year1pre=year1;
				int month1pre=month1-1;
				if(month1pre==0){
					year1pre=year1-1;
					month1pre=12;
				}
				String where2=" AND createtime<'"+year1+"-"+month1+"-06 00:00:00' AND createtime>='"+year1pre+"-"+month1pre+"-01 00:00:00'";
				if (orgidstr != null && orgidstr.length() > 0 && !orgidstr.equals("0")) {
					OrgEntity orgentity=iOrgService.GetOrgById(Long.parseLong(orgidstr));
					where2+=" AND userid IN (SELECT userid FROM t_sys_user where szdw in (SELECT orgid FROM t_sys_org WHERE lft>= "+orgentity.getLft()+" AND lft<="+orgentity.getRgt()+"))";
				} else {
					where2+=" AND userid IN(SELECT userid FROM t_sys_user WHERE 1=1 "+GetUserListByRole()+")";
				}
				where2+=" AND status=2";
				List<Map> kqjzqkMap = iStatisService.GetKqjzqkListByWhere(where2,year1,month1);
				data.put("kqjzqkMap", kqjzqkMap);
			}

			result.setCode(200);
			result.setResult(1);
			result.setMsg("操作成功");
			result.setItems(data);
		} catch (Exception ex) {
			result.setCode(500);
			result.setResult(0);
			result.setMsg("操作异常");
		}
		return result;
	}

	
	@LoginCheck(description = true)
	@ResponseBody
	@RequestMapping(value = "/getsummarylist")
	public LayTable<Map> GetSummaryList(HttpServletRequest request) {

		List<List<Map>> lst = null;
		LayTable<Map> layTable = new LayTable<Map>();
		try {
			int year =Integer.parseInt(request.getParameter("year")) ;
			int quarter =Integer.parseInt(request.getParameter("quarter")) ;
			
			String where = "";
			where+=this.GetUserListByRole();
            

            
			//String wherelimit=where+" ORDER BY C.orderindex ;
			List<Map> listMap=iStatisService.GetSummaryListByWhere(where,year,quarter);
			
			//lst = iStatisService.GetSummaryListByWhere(where,year,quarter);
			
			int iCount = 0;
			layTable.setCode(0);
			layTable.setCount(iCount);
			layTable.setData(listMap);

		} catch (Exception e) {
			layTable.setCode(500);
		}
		return layTable;
	}

	public String GetUserListByRole() {
		try {
			UserEntity entity = getWebSysUserAttribute("UserEntity");
			if (entity.getUserid() > 0) {
				String strorgids = iAccountService.GetOrgidsByUserRoleId(entity.getRoleid());
				if (strorgids != null && strorgids.length() > 0) {
					return " AND szdw IN (" + strorgids + ") ";
				} else {
					return " AND userid=" + entity.getUserid();
				}

			} else {
				return "";
			}
		} catch (Exception ex) {
			return null;
		}
	}

	public UserEntity getWebSysUserAttribute(String name) {
		UserEntity tuser = null;
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		if (ra != null) {
			HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
			if (!name.trim().equals("")) {
				tuser = (UserEntity) request.getSession().getAttribute(name);
			}
		}
		return tuser;
	}

	protected String renderStringScript(HttpServletResponse response, String string) {
		try {
			response.reset();
			response.setContentType("text/html");
			response.setCharacterEncoding("utf-8");
			response.getWriter().print(string);
			response.getWriter().flush();
			response.getWriter().close();
			return null;
		} catch (IOException e) {
			return null;
		}
	}

}
